<?php
/**
 * 公共函数助手类-
 */

namespace common\helpers;

class ShowFunction
{

    public static function getPostData()
    {
        $post_data = file_get_contents('php://input');
        $post_data = json_decode($post_data, true);
        return $post_data;
    }


    /**
     * 加密整型code
     * @param int $code 整型数据
     * @return string
     */
    public static function intEncryCode($code)
    {
        return self::dec62($code);
    }

    /**
     * 解密字符串code
     * @param string $code 加密后的字符串
     * @return number       解密后的整型
     */
    public static function intDecryCode($code)
    {
        return self::dec10($code);
    }

    /**
     * 可逆的字符串转62进制加密算法
     * @param int $num 需要加密的字符串
     * @return string     加密后的字符串
     */
    private static function dec62($num)
    {
        $to = 62;
        $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $ret = '';
        do {
            $ret = $dict[bcmod($num, $to)] . $ret; //bcmod取得高精确度数字的余数。
            $num = bcdiv($num, $to);  //bcdiv将二个高精确度数字相除。
        } while ($num > 0);
        return $ret;
    }

    /**
     * 可逆的62进制转字符串的解密算法
     * @param string $s 加密后的字符串
     * @return number       解密后的整型
     */
    private static function dec10($num)
    {
        $from = 62;
        $num = strval($num);
        $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $len = strlen($num);
        $dec = 0;
        for ($i = 0; $i < $len; $i++) {
            $pos = strpos($dict, $num[$i]);
            $dec = bcadd(bcmul(bcpow($from, $len - $i - 1), $pos), $dec);
        }
        return $dec;
    }


    /**
     * 数据加密
     * @param Array|String $data 加密的数据（可为数组，可为字符串）
     * @param String $key 秘钥
     * @return array
     */
    public function encrypt($data, $key = "betools") {

        $char = '';
        $str = '';
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $key = md5($key);
        $x = 0;
        $len = strlen($data);
        $l = strlen($key);
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }

    /**
     * 数据解密
     * @param String $data 加密后的数据字符串
     * @param String $key 秘钥
     * @return array
     */
    public function decrypt($data, $key = "betools") {

        $char = '';
        $str = '';
        $key = md5($key);
        $x = 0;
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);

        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            } else {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        if ($data = json_decode($str)) {
            return $data;
        }
        return $str;
    }


    /**
     * 写日志
     * @param string $module        模块名
     * @param string $data          日志内容字符串
     */
    public static function writeLog($module,$data)
    {
        $file_name = \Yii::$app->params['logDebugFile'];
        if (\Yii::$app->params['logDebug'] == true) {
            $log_file = self::get_yii_log() . "{$file_name}.log";
            if (!file_exists($log_file)) {
                exec("touch {$log_file}");
                exec("chmod 777 {$log_file}");
            }
            if(is_array($data)){
                $data = json_encode($data);
            }
            $data = date("Y-m-d H:i:s").$module."=>".$data;
            file_put_contents($log_file, $data . "\n", FILE_APPEND);
        }
    }


    public static function get_yii_log()
    {
        $yii_log = "/mydata/logs/yii_log/";
        // win 系统 走下面路径
        if (strpos(PHP_OS, "WIN") !== false) {
            $yii_log = "D:/www/logs/yii_log/";
        }
        return $yii_log;
    }


    /**
     * @author kevin
     * reader_me   不支持在控制器构造函数里面调用
     * @decription 返回当前请求的URL地址
     * @return string $url
     */
    public static function currentUrl()
    {
        $request = \Yii::$app->request;
        $controller = \Yii::$app->controller;
        $url = $request->getHostInfo() . $request->url;
        $url_arr = parse_url($url);
        $url = $url_arr['scheme'] . '://' . $url_arr['host'] . $url_arr['path'];
        if ($controller->action->id != basename(rtrim($url, '/'))) {
            $url = rtrim($url, '/') . '/' . $controller->action->id;
        }
        return $url;
    }

    /**
     * 获取客户端被代理前的IP
     */
    public static function realIp()
    {
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                foreach ($arr AS $ip) {
                    $ip = trim($ip);
                    if ($ip != 'unknown') {
                        $realip = $ip;
                        break;
                    }
                }
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            } else {
                if (isset($_SERVER['REMOTE_ADDR'])) {
                    $realip = $_SERVER['REMOTE_ADDR'];
                } else {
                    $realip = '0.0.0.0';
                }
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $realip = getenv('HTTP_X_FORWARDED_FOR');
            } elseif (getenv('HTTP_CLIENT_IP')) {
                $realip = getenv('HTTP_CLIENT_IP');
            } else {
                $realip = getenv('REMOTE_ADDR');
            }
        }
        preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
        $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
        return $realip;
    }


    /**
     * @decription 验证手机号码，是否合格
     * @param string $tel
     * @return bool
     */
    public static function verifyTel($tel = '')
    {
        $p = "/^1[1345789][\d]{9}$/";
        if (preg_match($p, $tel)) {
            return true;
        }
        return false;
    }

}